package cfg

import (
	"context"
	"fmt"
	"log"

	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// LinkMySQL 连接MySQL数据库，返回 *gorm.DB
func LinkMySQL(dbName string, logModel string, closeAffair bool) (*gorm.DB, error) {
	DSN := fmt.Sprintf(`%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local`,
		Password.MySQL.Account, Password.MySQL.Password, Password.MySQL.IP, Password.MySQL.Port, dbName)

	var lm logger.LogLevel
	switch logModel {
	case `Silent`:
		lm = logger.Silent
	case `Error`:
		lm = logger.Error
	case `Warn`:
		lm = logger.Warn
	case `Info`:
		lm = logger.Info
	default:
		lm = logger.Info
	}

	client, err := gorm.Open(mysql.Open(DSN), &gorm.Config{Logger: logger.Default.LogMode(lm), SkipDefaultTransaction: closeAffair})
	if err != nil {
		log.Println("连接 MySQL 数据库", dbName, "失败：", err)
		return nil, err
	}

	log.Println("连接 MySQL 数据库", dbName, "成功！")
	return client, nil
}

// LinkRedis 连接Redis数据库，返回 *redis.Client
func LinkRedis(dbNumber uint) (*redis.Client, error) {
	client := redis.NewClient(&redis.Options{
		Addr:       fmt.Sprint(Password.Redis.IP, ":", Password.Redis.Port),
		Username:   Password.Redis.Account,
		Password:   Password.Redis.Password,
		DB:         int(dbNumber),
		MaxRetries: 10, //命令最大重试次数
	})
	err := client.Ping(context.Background()).Err()
	if err != nil {
		log.Println("连接 Redis 数据库", dbNumber, "失败：", err)
		return nil, err
	}

	log.Println("连接 Redis 数据库", dbNumber, "成功！")
	return client, nil
}
